<?php

namespace App\Livewire;

use App\Models\Actor;
use App\Models\Favorite;
use App\Models\Video;
use Illuminate\Support\Collection;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class FavoriteList extends Component
{
    use WithPagination;

    public int $perPage = 4;

    public int $page = 1;

    public Collection $collection;

    public bool $hasMorePages;

    #[Url]
    public string $type = 'actor';

    public function mount(): void
    {
        $this->collection = Collection::make();

        $this->loadMore();
    }

    public function loadMore(): void
    {
        $collection = Favorite::hasMorph('favorite', $this->getType())
            ->simplePaginate(perPage: 8, page: $this->page);

        $this->collection->push(...$collection->items());

        if ($this->hasMorePages = $collection->hasMorePages()) {
            $this->page++;
        }
    }

    public function getType(): string
    {
        return match ($this->type) {
            'video' => Video::class,
            default => Actor::class,
        };
    }

    public function render()
    {
        return view('livewire.favorite-list');
    }
}
